package com.woniuxy.gateway.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/9 0009-下午 8:59
 */
public class Jwtutil {
    public static String createToken(Date expireDate, Map claims){
        return  Jwts.builder()

                .setIssuedAt(new Date()) //token签发时间
                .setExpiration(expireDate) //token过期时间
                .setHeaderParam("typ","JWT")
                .setClaims(claims)//自定义的数据
                //参数1是密钥对的私钥
                .signWith(getKeyPair().getPrivate(), SignatureAlgorithm.RS256) //指定加密算法及秘钥
                .compact();

    }

    /**
     * 生成密钥对
     * @return
     */
    public static KeyPair getKeyPair(){
        //加载秘钥库文件
        ClassPathResource resource = new ClassPathResource("sec.jks");
        //参数2是访问秘钥库的密码
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(resource,"helloworld".toCharArray());
        return factory.getKeyPair("seckey","testHello".toCharArray());
    }

    public static Map parseToken(String token){
        return Jwts.parserBuilder().setSigningKey(getKeyPair().getPublic()).build().parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) {
        Date expireDate = DateTime.now().plusDays(2).toDate();
        Map claims = new HashMap();
        claims.put("userId",1001);
        claims.put("username","lisi");
        String token = createToken(expireDate, claims);
        System.out.println(token);
    }
}
